<template lang="pug">
div
  multiselect(
    :selected="selected",
    :options="options",
    @update="updateSelected",
    :allow-empty="false",
    :local-search="localSearch",
    :searchable="searchable",
    :key="key",
    :placeholder="placeholder",
    :label="label",
    :show-labels="false",
    :custom-label="computedCustomLabel",
    :loading="loading",
    :close-on-select="closeOnSelect",
    @search-change="computedSearchChange",
  )
</template>

<script>
import Multiselect from 'vue-multiselect'

export default {
  name: 'objSingleSelect',
  components: {
    Multiselect,
  },
  props: {
    closeOnSelect: null,
    localSearch: null,
    searchable: {
      default: false
    },
    placeholder: null,
    options: null,
    key: null,
    label: null,
    update: null,
    value: null,
    text: null,
    selected: null,
    type: null,
    customLabel: null,
    searchChange: null,
    loading: null,
  },
  data () {
    return {
    }
  },
  methods: {
    updateSelected (val) {
      /*if (_.isObject(this.selected)) {
        this.selected = _.assign(this.selected, val)
      } else {
        this.selected = val
      }*/
       
      this.selected = val
       
      if (val) {
        this.value  = val[this.key]
        this.text  = val[this.label]
      }
      if (_.isFunction(this.update)) {
        this.update(val)
      }
    },
  },
  computed: {
    computedCustomLabel () {
      return _.isFunction(this.customLabel) ? this.customLabel : selected => selected[this.label]
    },
    computedSearchChange () {
      return _.isFunction(this.searchChange) ? this.searchChange : () => {}
    },
  },
  watch: {
    selected: {
      handler (val, old) {
        if (this.type !== 'selected' || !val) {
          return
        }
        this.value  = val[this.key]
        this.text  = val[this.label]
      },
      deep: true,
      immediate: true,
    },
    'value+options': {
      handler (val, old) {
        if (this.type !== 'value') {
          return
        }
        this.selected = _.find(this.options, [this.key, this.value])
      },
      deep: true,
      immediate: true,
    },
    'text+options': {
      handler (val, old) {
        if (this.type !== 'text') {
          return
        }
        this.selected = _.find(this.options, [this.label, this.text])
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style lang="sass" scoped>
</style>
